import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ThemeService with ChangeNotifier {
  static const String _themeModeKey = 'theme_mode';
  static const String _lightPrimaryColorKey = 'light_primary_color';
  static const String _darkPrimaryColorKey = 'dark_primary_color';

  // 单例模式
  static final ThemeService _instance = ThemeService._internal();
  ThemeMode _themeMode = ThemeMode.system;

  Color _lightPrimaryColor = Color(0xFF18181B);
  Color _darkPrimaryColor = Color(0xFFFFFFFF);
  factory ThemeService() => _instance;

  ThemeService._internal();

  // 默认深色主题
  ThemeData get darkTheme => ThemeData(
    useMaterial3: true,
    colorScheme: ColorScheme.dark(
      primary: _darkPrimaryColor,
      secondary: _darkPrimaryColor.withOpacity(0.8),
      surface: Colors.grey[900]!,
    ),
    appBarTheme: AppBarTheme(
      backgroundColor: Colors.grey[900]!,
      elevation: 0,
      iconTheme: const IconThemeData(color: Colors.white),
      titleTextStyle: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
    ),
    cardTheme: CardTheme(
      elevation: 1,
      margin: EdgeInsets.zero,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
    ),
  );

  bool get isDarkMode {
    if (_themeMode == ThemeMode.system) {
      return WidgetsBinding.instance.window.platformBrightness == Brightness.dark;
    }
    return _themeMode == ThemeMode.dark;
  }

  // 默认浅色主题
  ThemeData get lightTheme => ThemeData(
    useMaterial3: true,
    colorScheme: ColorScheme.light(
      primary: _lightPrimaryColor,
      secondary: _lightPrimaryColor.withOpacity(0.8),
      surface: Colors.white,
    ),
    appBarTheme: AppBarTheme(
      backgroundColor: Colors.white,
      elevation: 0,
      iconTheme: const IconThemeData(color: Colors.black87),
      titleTextStyle: TextStyle(color: Colors.black87, fontSize: 20, fontWeight: FontWeight.bold),
    ),
    cardTheme: CardTheme(
      elevation: 1,
      margin: EdgeInsets.zero,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
    ),
  );

  Color get primaryColor => isDarkMode ? _darkPrimaryColor : _lightPrimaryColor;
  ThemeMode get themeMode => _themeMode;

  Future<void> init() async {
    final prefs = await SharedPreferences.getInstance();

    // 加载主题模式
    final mode = prefs.getString(_themeModeKey);
    _themeMode = _parseThemeMode(mode);

    // 加载自定义颜色
    _lightPrimaryColor = Color(prefs.getInt(_lightPrimaryColorKey) ?? _lightPrimaryColor.value);
    _darkPrimaryColor = Color(prefs.getInt(_darkPrimaryColorKey) ?? _darkPrimaryColor.value);

    // 监听系统主题变化
    WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged = () {
      if (_themeMode == ThemeMode.system) {
        notifyListeners();
      }
    };
  }

  Future<void> setColors({Color? lightPrimary, Color? darkPrimary}) async {
    final prefs = await SharedPreferences.getInstance();

    if (lightPrimary != null) {
      _lightPrimaryColor = lightPrimary;
      await prefs.setInt(_lightPrimaryColorKey, lightPrimary.value);
    }

    if (darkPrimary != null) {
      _darkPrimaryColor = darkPrimary;
      await prefs.setInt(_darkPrimaryColorKey, darkPrimary.value);
    }

    notifyListeners();
  }

  Future<void> setThemeMode(ThemeMode mode) async {
    _themeMode = mode;
    notifyListeners();

    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_themeModeKey, mode.toString().split('.').last);
  }

  ThemeMode _parseThemeMode(String? mode) {
    switch (mode) {
      case 'light':
        return ThemeMode.light;
      case 'dark':
        return ThemeMode.dark;
      default:
        return ThemeMode.system;
    }
  }
}
